#include <modules\graphics\opengl\opengl_graphics_context.h>

namespace DelGE
{
	namespace Modules
	{
		namespace Graphics
		{
			OpenGLGraphicsContext::OpenGLGraphicsContext(SystemGadget* pSystemGadget)
			{
				#if defined(DELGE_PLATFORM_WIN32)
				this->hWnd = pSystemGadget->GetInterfaceGadget()->GetHWND();
				this->hDC = pSystemGadget->GetInterfaceGadget()->GetHDC();
				#endif
				this->CreateGraphicsContext();
			}

			OpenGLGraphicsContext::~OpenGLGraphicsContext()
			{
				this->DestroyGraphicsContext();
			}

			#if defined(DELGE_PLATFORM_WIN32)
			OpenGLGraphicsContext::OpenGLGraphicsContext(HWND hWnd)
			{
				this->hWnd = hWnd;
				this->hDC = GetDC(this->hWnd);
				this->CreateGraphicsContext();
			}

			void OpenGLGraphicsContext::CreateGraphicsContext()
			{
				int iPixelFormat;

				PIXELFORMATDESCRIPTOR pixelFormatDescriptor = 
				{
					sizeof(PIXELFORMATDESCRIPTOR),
					1,
					PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
					PFD_TYPE_RGBA,
					16,
					0, 0, 0, 0, 0, 0, 
					0, 
					0, 
					0, 
					0, 0, 0, 0,
					16,
					0,
					0, 
					PFD_MAIN_PLANE, 
					0, 
					0, 0, 0 
				};

				iPixelFormat = ChoosePixelFormat(this->hDC, &pixelFormatDescriptor);
				if (!iPixelFormat)
				{}// could not find a sutiable pixel format

				BOOL bSetFormat = SetPixelFormat(this->hDC, iPixelFormat, &pixelFormatDescriptor);
				if (!bSetFormat)
				{}// could not set the format

				// Create the context resource and then make it current
				this->hRC = wglCreateContext(this->hDC);
				this->MakeCurrent();

				// Now we have context, we can start glew
				glewInit();
			}

			void OpenGLGraphicsContext::DestroyGraphicsContext()
			{
				wglMakeCurrent(this->hDC, NULL);
				wglDeleteContext(this->hRC);
			}

			void OpenGLGraphicsContext::SwapBuffers()
			{
				::SwapBuffers(this->hDC);
			}

			void OpenGLGraphicsContext::MakeCurrent()
			{
				wglMakeCurrent(this->hDC, this->hRC);

				glEnable(GL_CULL_FACE);
				glEnable(GL_TEXTURE_2D);
				glDisable(GL_LIGHTING);
				glEnable(GL_COLOR_MATERIAL);
				glFrontFace(GL_CW);
			}

			int OpenGLGraphicsContext::GetWidth()
			{
				RECT windowRect;

				GetClientRect(this->hWnd, &windowRect);

				return windowRect.right;
			}
			
			int OpenGLGraphicsContext::GetHeight()
			{
				RECT windowRect;

				GetClientRect(this->hWnd, &windowRect);

				return windowRect.bottom;
			}
			#endif
		}
	}
}